package com.example.blackmarket.module.SecondHandTrade.PostingSellOrWant;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.example.blackmarket.R;
import com.example.blackmarket.entities.GetInformationSuccessRespond;
import com.example.blackmarket.entities.SuccessResponse;
import com.example.blackmarket.module.Base.BaseActivity;
import com.example.blackmarket.module.Base.BaseApplication;
import com.example.blackmarket.module.RegisterAndLogin.LoginActivity;
import com.example.blackmarket.module.SecondHandTrade.PostingSuccess.PostingSuccessActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.example.blackmarket.module.Base.BaseApplication.showToast;

public class PostingSellOrWantActivity extends BaseActivity implements PostingSellOrWantView{//    private Button posting_back;
    private ImageButton posting_back;
    private ImageButton posting_confirm;
    private Spinner type;
    private Spinner campus;
    private TextView shoppingGuideName;
    private TextView shoppingGuidePrice;
    private TextView shoppingGuideDescription;
    private ImageView add_photo_btn;
    private ImageView shoppingGuidePictureLocation;
    private PostingSellOrWantPresenter postingSellOrWantPresenter;


    private int type1;
    private String shoppingGuideBuyerId;

    private String imagePath;
    private Uri imageUri;
    public static final int TAKE_PHOTO=1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.init();
        postingSellOrWantPresenter=new PostingSellOrWantPresenter(this);

        //首先获取用户的student的ID
        shoppingGuideBuyerId= BaseApplication.get("studentNumber","201830661168");
//        postingSellOrWantPresenter.getStudentId();
//        Log.d("学生学号",shoppingGuideBuyerId);
    }
    @Override
    protected void onBindView(){
        posting_back=findViewById(R.id.posting_back);
        posting_confirm=findViewById(R.id.posting_confirm);
        type=findViewById(R.id.spinnerType);
        campus=findViewById(R.id.spinnerPlace);
        shoppingGuideName=findViewById(R.id.postOrWant_title);
        shoppingGuideDescription=findViewById(R.id.postOrWant_description);
        shoppingGuidePrice=findViewById(R.id.postOrWant_price);
        shoppingGuidePictureLocation=findViewById(R.id.postOrWant_photo);
        add_photo_btn=findViewById(R.id.add_photo_btn);
    }
    @Override
    protected void setButtonClick(){
        posting_confirm.setOnClickListener(this);
        posting_back.setOnClickListener(this);
        add_photo_btn.setOnClickListener(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.posting_sell_or_want;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //返回上一页
            case R.id.posting_back:{
                finish();
                break;
            }
            //确认发布
            case R.id.posting_confirm:{
                Log.d("出售求购",type.getSelectedItem().toString());
                Log.d("南校北校？",campus.getSelectedItem().toString());
                Log.d("名称",shoppingGuideName.getText().toString());
                Log.d("商品价格",shoppingGuidePrice.getText().toString());
                Log.d("商品描述",shoppingGuideDescription.getText().toString());
                Log.d("学生学号",shoppingGuideBuyerId);

                //输入信息完整的话
                if(isComplete()){
                    postingSellOrWantPresenter.postingData(type.getSelectedItem().toString(),campus.getSelectedItem().toString(),shoppingGuideBuyerId,shoppingGuideDescription.getText().toString(),shoppingGuideName.getText().toString(),imagePath,Double.parseDouble(shoppingGuidePrice.getText().toString()));
                }
                break;
            }
            //添加图片
            case R.id.add_photo_btn:{
                askForPermission();
                break;
            }
            default:break;
        }
    }

    public void askForPermission(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
//            Log.e("permission","ask for permission");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }else{
            pickImageFromAlbum();
        }
    }

    public void pickImageFromAlbum(){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.setType("image/*");
        startActivityForResult(intent,111);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1:{
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    pickImageFromAlbum();
                }else{
                    showToast("you denied the permission");
                }
                break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 111:{
                if(resultCode == RESULT_CANCELED){
                    showToast("已取消选择");
                    return;
                }
                try{
                    //获取图片的uri并转换成路径
                    imageUri = data.getData();
                    imagePath = getImagePath(imageUri);
                    Log.d("imagepath ",imagePath);
                    //显示这张图片
                    shoppingGuidePictureLocation.setImageURI(imageUri);
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            }
            default:
                break;

        }
    }

    private  String getImagePath(Uri uri) {
        String path = null;
        Cursor cursor = this.getContentResolver().query(uri, null, String.valueOf(new String[]{MediaStore.Images.ImageColumns.DATA}), null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    @Override
    public void postData(long posterId, double price, String place, String title, String description, String imageUrl) {

    }

    @Override
    public void postSuccess(Object data) {
        SuccessResponse successResponse = (SuccessResponse)data;
        boolean success = successResponse.getSuccess();
        if (success){
            Toast.makeText(this, successResponse.getMessage(),Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, PostingSuccessActivity.class);
            startActivity(intent);
        }
        else
            Toast.makeText(this, successResponse.getMessage(),Toast.LENGTH_SHORT).show();
    }


    @Override
    public void getStudentIdSuccess(Object data) {
        GetInformationSuccessRespond getInformationSuccessRespond=(GetInformationSuccessRespond)data;
        String studentId=getInformationSuccessRespond.getStudentNumber();
        shoppingGuideBuyerId=studentId;
    }

    @Override
    public void postFailure(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    //判断输入是否完整
    public boolean isComplete(){
        //判断是否输入标题
        if(shoppingGuideName.getText().toString()==null||shoppingGuideName.getText().toString().equals("")){
            Toast.makeText(this,"请输入标题",Toast.LENGTH_SHORT).show();
            return false;
        }
        //判断是否输入价格
        if(shoppingGuidePrice.getText().toString()==null||shoppingGuidePrice.getText().toString().equals("")){
            Toast.makeText(this,"请输入价格",Toast.LENGTH_SHORT).show();
            return false;
        }

        //判断输入的价格是否合法
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(shoppingGuidePrice.getText().toString());
        if(!m.matches() ){
            Toast.makeText(this,"请输入合法数字", Toast.LENGTH_SHORT).show();
            return false;
        }

        //判断是否输入商品描述
        if(shoppingGuideDescription.getText().toString()==null||shoppingGuideDescription.getText().toString().equals("")){
            Toast.makeText(this,"请输入商品描述",Toast.LENGTH_SHORT).show();
            return false;
        }
        //判断是否添加图片
        if(imagePath==null){
            Toast.makeText(this,"请添加图片",Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;

    }
}
